<template>
  <view class="container">
    <view class="header">
      <text class="title">AI对话测试</text>
    </view>
    
    <view class="form-section">
      <text class="section-title">创建会话</text>
      
      <view class="form-item">
        <text class="label">结果ID:</text>
        <input class="input" v-model="resultId" placeholder="输入分析结果ID"/>
      </view>
      
      <view class="form-item">
        <text class="label">用户ID:</text>
        <input class="input" v-model="userId" placeholder="输入用户ID"/>
      </view>
      
      <view class="form-item">
        <text class="label">运动类型:</text>
        <input class="input" v-model="sportType" placeholder="输入运动类型"/>
      </view>
      
      <button class="btn primary" @click="createConversation" :disabled="isLoading">创建会话</button>
      <button class="btn secondary" @click="createConversationAgain" :disabled="isLoading" style="margin-top: 10px;">再次创建会话（测试一对一）</button>
    </view>
    
    <view class="result-section" v-if="conversationId">
      <text class="section-title">会话ID: {{ conversationId }}</text>
      
      <view class="form-item">
        <text class="label">问题:</text>
        <input class="input" v-model="question" placeholder="输入问题"/>
      </view>
      
      <button class="btn secondary" @click="askQuestion" :disabled="isLoading || !question">发送问题</button>
      
      <view class="messages-container">
        <view v-for="(message, index) in messages" :key="index" :class="['message', message.senderType === 'USER' ? 'user-message' : 'ai-message']">
          <text class="message-sender">{{ message.senderType === 'USER' ? '用户' : 'AI' }}</text>
          <text class="message-content">{{ message.content }}</text>
        </view>
      </view>
      
      <button class="btn danger" @click="endConversation" :disabled="isLoading">结束会话</button>
    </view>
    
    <view class="log-section">
      <text class="section-title">请求日志</text>
      <scroll-view class="log-container" scroll-y>
        <text class="log-content">{{ logContent }}</text>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { createConversation as apiCreateConversation, askQuestion as apiAskQuestion, endConversation as apiEndConversation } from '@/api/modules/AiGuidance.js'

// 表单数据
const resultId = ref('') // 动态获取
const userId = ref('') // 动态获取
const sportType = ref('general')
const question = ref('')

// 状态
const isLoading = ref(false)
const conversationId = ref('')
const messages = ref([])
const logContent = ref('')

// 初始化页面参数
const initializePageParams = () => {
  // 从页面参数获取
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options
  
  if (options.resultId) {
    resultId.value = options.resultId
  }
  
  // 获取当前用户ID
  try {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo && userInfo.id) {
      userId.value = typeof userInfo.id === 'string' ? userInfo.id : userInfo.id.toString()
    }
  } catch (error) {
    console.error('获取用户ID失败:', error)
  }
  
  if (options.sportType) {
    sportType.value = options.sportType
  }
}

// 页面加载时初始化
onMounted(() => {
  initializePageParams()
})

// 添加日志
const addLog = (message) => {
  const timestamp = new Date().toLocaleTimeString()
  logContent.value += `[${timestamp}] ${message}\n`
}

// 创建会话
const createConversation = async () => {
  if (!resultId.value || !userId.value || !sportType.value) {
    uni.showToast({
      title: '请填写所有必填字段',
      icon: 'none'
    })
    return
  }
  
  isLoading.value = true
  addLog('开始创建会话...')
  
  try {
    const requestData = {
      resultId: resultId.value,
      userId: userId.value,
      sportType: sportType.value
    }
    
    addLog(`请求数据: ${JSON.stringify(requestData)}`)
    
    const response = await apiCreateConversation(requestData)
    
    addLog(`响应数据: ${JSON.stringify(response)}`)
    
    if (response && response.conversationId) {
      conversationId.value = response.conversationId
      
      // 添加欢迎消息
      if (response.messages && response.messages.length > 0) {
        messages.value = response.messages
      }
      
      uni.showToast({
        title: '会话创建成功',
        icon: 'success'
      })
    } else {
      throw new Error('未获取到会话ID')
    }
  } catch (error) {
    addLog(`创建会话失败: ${error.message || JSON.stringify(error)}`)
    
    uni.showToast({
      title: '创建会话失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 发送问题
const askQuestion = async () => {
  if (!conversationId.value || !question.value) return
  
  isLoading.value = true
  addLog(`发送问题: ${question.value}`)
  
  // 添加用户消息
  messages.value.push({
    messageId: `temp-${Date.now()}`,
    content: question.value,
    senderType: 'USER'
  })
  
  try {
    const requestData = {
      conversationId: conversationId.value,
      question: question.value
    }
    
    addLog(`请求数据: ${JSON.stringify(requestData)}`)
    
    const response = await apiAskQuestion(requestData)
    
    addLog(`响应数据: ${JSON.stringify(response)}`)
    
    if (response) {
      // 添加AI回复
      messages.value.push({
        messageId: response.messageId || `ai-${Date.now()}`,
        content: response.content || '无回复内容',
        senderType: 'AI_ASSISTANT'
      })
      
      // 清空输入框
      question.value = ''
    }
  } catch (error) {
    addLog(`发送问题失败: ${error.message || JSON.stringify(error)}`)
    
    uni.showToast({
      title: '发送问题失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 结束会话
const endConversation = async () => {
  if (!conversationId.value) return
  
  isLoading.value = true
  addLog(`结束会话: ${conversationId.value}`)
  
  try {
    await apiEndConversation(conversationId.value)
    
    addLog('会话已结束')
    
    // 添加系统消息
    messages.value.push({
      messageId: `system-${Date.now()}`,
      content: '会话已结束',
      senderType: 'AI_ASSISTANT'
    })
    
    uni.showToast({
      title: '会话已结束',
      icon: 'success'
    })
  } catch (error) {
    addLog(`结束会话失败: ${error.message || JSON.stringify(error)}`)
    
    uni.showToast({
      title: '结束会话失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}
</script>

<style>
.container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 15px 0;
  color: #444;
}

.form-section, .result-section, .log-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.form-item {
  margin-bottom: 15px;
}

.label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #555;
}

.input {
  width: 100%;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 14px;
}

.btn {
  width: 100%;
  height: 44px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  margin-top: 10px;
}

.primary {
  background-color: #4a6cf7;
  color: white;
}

.secondary {
  background-color: #6c757d;
  color: white;
}

.danger {
  background-color: #dc3545;
  color: white;
}

.messages-container {
  margin: 20px 0;
  max-height: 300px;
  overflow-y: auto;
}

.message {
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 8px;
}

.user-message {
  background-color: #e9ecef;
  margin-left: 20px;
}

.ai-message {
  background-color: #e3f2fd;
  margin-right: 20px;
}

.message-sender {
  font-weight: bold;
  font-size: 12px;
  margin-bottom: 5px;
  display: block;
}

.message-content {
  font-size: 14px;
  line-height: 1.4;
}

.log-container {
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  height: 200px;
  font-family: monospace;
}

.log-content {
  white-space: pre-wrap;
  font-size: 12px;
  color: #666;
}
</style> 
  <view class="container">
    <view class="header">
      <text class="title">AI对话测试</text>
    </view>
    
    <view class="form-section">
      <text class="section-title">创建会话</text>
      
      <view class="form-item">
        <text class="label">结果ID:</text>
        <input class="input" v-model="resultId" placeholder="输入分析结果ID"/>
      </view>
      
      <view class="form-item">
        <text class="label">用户ID:</text>
        <input class="input" v-model="userId" placeholder="输入用户ID"/>
      </view>
      
      <view class="form-item">
        <text class="label">运动类型:</text>
        <input class="input" v-model="sportType" placeholder="输入运动类型"/>
      </view>
      
      <button class="btn primary" @click="createConversation" :disabled="isLoading">创建会话</button>
      <button class="btn secondary" @click="createConversationAgain" :disabled="isLoading" style="margin-top: 10px;">再次创建会话（测试一对一）</button>
    </view>
    
    <view class="result-section" v-if="conversationId">
      <text class="section-title">会话ID: {{ conversationId }}</text>
      
      <view class="form-item">
        <text class="label">问题:</text>
        <input class="input" v-model="question" placeholder="输入问题"/>
      </view>
      
      <button class="btn secondary" @click="askQuestion" :disabled="isLoading || !question">发送问题</button>
      
      <view class="messages-container">
        <view v-for="(message, index) in messages" :key="index" :class="['message', message.senderType === 'USER' ? 'user-message' : 'ai-message']">
          <text class="message-sender">{{ message.senderType === 'USER' ? '用户' : 'AI' }}</text>
          <text class="message-content">{{ message.content }}</text>
        </view>
      </view>
      
      <button class="btn danger" @click="endConversation" :disabled="isLoading">结束会话</button>
    </view>
    
    <view class="log-section">
      <text class="section-title">请求日志</text>
      <scroll-view class="log-container" scroll-y>
        <text class="log-content">{{ logContent }}</text>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { createConversation as apiCreateConversation, askQuestion as apiAskQuestion, endConversation as apiEndConversation } from '@/api/modules/AiGuidance.js'

// 表单数据
const resultId = ref('ec7b5c21-8660-48c6-bade-a1a876006794')
const userId = ref('3')
const sportType = ref('general')
const question = ref('')

// 状态
const isLoading = ref(false)
const conversationId = ref('')
const messages = ref([])
const logContent = ref('')

// 添加日志
const addLog = (message) => {
  const timestamp = new Date().toLocaleTimeString()
  logContent.value += `[${timestamp}] ${message}\n`
}

// 创建会话
const createConversation = async () => {
  if (!resultId.value || !userId.value || !sportType.value) {
    uni.showToast({
      title: '请填写所有必填字段',
      icon: 'none'
    })
    return
  }
  
  isLoading.value = true
  addLog('开始创建会话...')
  
  try {
    const requestData = {
      resultId: resultId.value,
      userId: userId.value,
      sportType: sportType.value
    }
    
    addLog(`请求数据: ${JSON.stringify(requestData)}`)
    
    const response = await apiCreateConversation(requestData)
    
    addLog(`响应数据: ${JSON.stringify(response)}`)
    
    if (response && response.conversationId) {
      conversationId.value = response.conversationId
      
      // 添加欢迎消息
      if (response.messages && response.messages.length > 0) {
        messages.value = response.messages
      }
      
      uni.showToast({
        title: '会话创建成功',
        icon: 'success'
      })
    } else {
      throw new Error('未获取到会话ID')
    }
  } catch (error) {
    addLog(`创建会话失败: ${error.message || JSON.stringify(error)}`)
    
    uni.showToast({
      title: '创建会话失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 发送问题
const askQuestion = async () => {
  if (!conversationId.value || !question.value) return
  
  isLoading.value = true
  addLog(`发送问题: ${question.value}`)
  
  // 添加用户消息
  messages.value.push({
    messageId: `temp-${Date.now()}`,
    content: question.value,
    senderType: 'USER'
  })
  
  try {
    const requestData = {
      conversationId: conversationId.value,
      question: question.value
    }
    
    addLog(`请求数据: ${JSON.stringify(requestData)}`)
    
    const response = await apiAskQuestion(requestData)
    
    addLog(`响应数据: ${JSON.stringify(response)}`)
    
    if (response) {
      // 添加AI回复
      messages.value.push({
        messageId: response.messageId || `ai-${Date.now()}`,
        content: response.content || '无回复内容',
        senderType: 'AI_ASSISTANT'
      })
      
      // 清空输入框
      question.value = ''
    }
  } catch (error) {
    addLog(`发送问题失败: ${error.message || JSON.stringify(error)}`)
    
    uni.showToast({
      title: '发送问题失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 结束会话
const endConversation = async () => {
  if (!conversationId.value) return
  
  isLoading.value = true
  addLog(`结束会话: ${conversationId.value}`)
  
  try {
    await apiEndConversation(conversationId.value)
    
    addLog('会话已结束')
    
    // 添加系统消息
    messages.value.push({
      messageId: `system-${Date.now()}`,
      content: '会话已结束',
      senderType: 'AI_ASSISTANT'
    })
    
    uni.showToast({
      title: '会话已结束',
      icon: 'success'
    })
  } catch (error) {
    addLog(`结束会话失败: ${error.message || JSON.stringify(error)}`)
    
    uni.showToast({
      title: '结束会话失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}
</script>

<style>
.container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 15px 0;
  color: #444;
}

.form-section, .result-section, .log-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.form-item {
  margin-bottom: 15px;
}

.label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #555;
}

.input {
  width: 100%;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 14px;
}

.btn {
  width: 100%;
  height: 44px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  margin-top: 10px;
}

.primary {
  background-color: #4a6cf7;
  color: white;
}

.secondary {
  background-color: #6c757d;
  color: white;
}

.danger {
  background-color: #dc3545;
  color: white;
}

.messages-container {
  margin: 20px 0;
  max-height: 300px;
  overflow-y: auto;
}

.message {
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 8px;
}

.user-message {
  background-color: #e9ecef;
  margin-left: 20px;
}

.ai-message {
  background-color: #e3f2fd;
  margin-right: 20px;
}

.message-sender {
  font-weight: bold;
  font-size: 12px;
  margin-bottom: 5px;
  display: block;
}

.message-content {
  font-size: 14px;
  line-height: 1.4;
}

.log-container {
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  height: 200px;
  font-family: monospace;
}

.log-content {
  white-space: pre-wrap;
  font-size: 12px;
  color: #666;
}
</style> 
 